import os
from concurrent.futures import ThreadPoolExecutor
from itertools import repeat
from pathlib import Path

def remove_mtext_and_blocks(dxf_path: str, output_path: str) -> None:
    """
    清除 DXF 文件中的多行文字（MTEXT）和块（BLOCK），并保存为新的 DXF 文件。
    """
    import ezdxf
    doc = ezdxf.readfile(dxf_path)
    msp = doc.modelspace()

    # 删除所有 MText 实体
    for mtext in msp.query("MTEXT"):
        msp.delete_entity(mtext)

    # 删除所有 Block 引用（INSERT 实体）
    for insert in msp.query("INSERT"):
        msp.delete_entity(insert)

    # 删除所有用户自定义 Block（不包括 Model/Paper Space）
    block_names = [name for name in doc.blocks.block_names() if not name.startswith("*")]
    for name in block_names:
        try:
            del doc.blocks[name]
        except Exception as e:
            print(f"⚠️ 无法删除块 {name}：{e}")

    doc.saveas(output_path)




# 清除函数封装（调用你提供的函数）
def clean_dxf(dxf_path,output_dir):
    try:
        name = Path(dxf_path).stem
        cleaned_path = os.path.join(output_dir, f"{name}_cleaned.dxf")
        remove_mtext_and_blocks(dxf_path, cleaned_path)
        print(f"✅ 完成清理: {dxf_path}")
        return {"file": dxf_path, "success": True}
    except Exception as e:
        print(f"❌ 清理失败: {dxf_path}，错误: {e}")
        return {"file": dxf_path, "success": False, "error": str(e)}


def concurrent_remove_noise(dxf_files):
    print(f'Here is dxf:{dxf_files}')
    output_dir = "清除后的图纸"
    os.makedirs(output_dir, exist_ok=True)
    graph_path_list = []
    with ThreadPoolExecutor(max_workers=7) as executor:
        results = list(executor.map(clean_dxf, dxf_files, repeat(output_dir)))
        for result in results:
            graph_path_list.append(result.get('file'))
    return graph_path_list

if __name__ == "__main__":
    dxf_files = [
        r"E:\cadsecond-processing\output\model1_A3_1_20250716_103202_697.dxf",
        r"E:\cadsecond-processing\output\model1_A3_2_20250716_103205_984.dxf",
        r"E:\cadsecond-processing\output\model1_A3_3_20250716_103209_342.dxf",
        r"E:\cadsecond-processing\output\model1_A3_4_20250716_103212_813.dxf",
        r"E:\cadsecond-processing\output\model1_A3_5_20250716_103216_264.dxf",
        r"E:\cadsecond-processing\output\model1_A3_6_20250716_103219_734.dxf",
        r"E:\cadsecond-processing\output\model1_A3_7_20250716_103223_197.dxf"
    ]

    print(concurrent_remove_noise(dxf_files))